package com.company.project.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.company.project.entity.AdCost;
import com.company.project.entity.CostEntity;
import com.company.project.mapper.AdCostMapper;
import com.company.project.mapper.CostMapper;
import com.company.project.service.AdCostService;
import com.company.project.service.SysCostService;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;


@Service("sysCostService")
public class SysCostServiceImpl extends ServiceImpl<CostMapper, CostEntity> implements SysCostService {

    @Autowired
    private AdCostService adCostService;

    @Override
    public boolean calculateAdCost(List<CostEntity> costEntities) {

        if (CollectionUtils.isEmpty(costEntities)) {
            return false;
        }
        // k name:month v totalCost
        Map<String, Double> adCostMap = Maps.newHashMap();
        for (CostEntity costEntity : costEntities) {
            String name = costEntity.getJdPerson();
            Double adPrice = costEntity.getAdPrice();
            Date createTime = costEntity.getCreateTime();
            Calendar cal = Calendar.getInstance();
            cal.setTime(createTime);
            int month = cal.get(Calendar.MONTH)+1;
            String key = name + ":" + month;
            Double lastAdPrice = adCostMap.get(key);
            adCostMap.put(key, lastAdPrice == null ? adPrice : lastAdPrice + adPrice);
        }
        if (adCostMap.size() == 0) {
            return false;
        }
        Set<String> names = Sets.newHashSet();
        adCostMap.forEach((k, v) -> {
            String[] kArr = k.split(":");
            names.add(kArr[0]);
        });
        QueryWrapper<AdCost> qw = new QueryWrapper<>();
        qw.eq("is_delete", 0).in("name", names);
        List<AdCost> adCosts = adCostService.list(qw);
        Map<String, Map<String, Double>> historyAdCostMap = Maps.newHashMap();
        if (!CollectionUtils.isEmpty(adCosts)) {
            historyAdCostMap = adCosts.stream().collect(Collectors.toMap(item -> item.getName(), item -> toMonthCostMap(item)));
        }
        Map<String, AdCost> name2adCost = new HashMap<>();
        for (Map.Entry<String, Double> item : adCostMap.entrySet()) {
            String[] kArr = item.getKey().split(":");
            Double currCost = item.getValue();
            String name = kArr[0];
            String month = kArr[1];
            AdCost adCost = name2adCost.get(name);
            if (adCost == null) {
                adCost = new AdCost();
                adCost.setIsDelete(0);
                adCost.setCreateTime(new Date());

                name2adCost.put(name, adCost);
            }
            adCost.setUpdateTime(new Date());
            Map<String, Double> monthCostMap = historyAdCostMap.get(name);
            if (monthCostMap == null) {
                monthCostMap = new HashMap<>();
            }
            Double itemCost = monthCostMap.getOrDefault(month, 0.0);
            monthCostMap.put(month, itemCost + currCost);
            adCost.setMonthCost(JSON.toJSONString(monthCostMap));
        }
        adCostService.saveOrUpdateBatch(name2adCost.values());
        return true;
    }

    private Map<String, Double> toMonthCostMap(AdCost item) {
        return JSON.parseObject(item.getMonthCost(), Map.class);
    }

}